package org.dwell.urlfilter.demo.controller;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.context.ServletContextAware;

import javax.servlet.ServletContext;
import javax.servlet.http.HttpServletRequest;

/**
 * Created by Jange on 2016/4/6.
 */
@Controller("baseController")
public class BaseController implements ServletContextAware {
    // 实现ServletContextAware接口，只要实现setServletContext方法，即可自动注入servletContext的实例
    protected ServletContext servletContext;

    public void setServletContext(ServletContext servletContext)
    {
        this.servletContext = servletContext;
    }

    /**
     * 在所有的控制器返回的时候绑定参数，
     * 这里绑定了一个bp的参数，值是请求的基本路径，比如系统在本地运行，ctx就是http://localhost:8080/  ctxStatic = http://localhost:8080/static
     * 在页面上使用EL表达式来取得项目基路径地址${ctx}、${ctxStatic}
     */
    @ModelAttribute("request")
    public HttpServletRequest getRequest( HttpServletRequest request )
    {
        String path = request.getContextPath();
        String basePath = request.getScheme() + "://" + request.getServerName() + ":" + request.getServerPort() + path;
        String staticPath = basePath + "/static";
        request.setAttribute("ctx", basePath);
        request.setAttribute("ctxStatic",staticPath);
        return request;
    }

    protected String getBasePath(HttpServletRequest request) {
        String path = request.getContextPath();
        return request.getScheme() + "://" + request.getServerName() + ":" + request.getServerPort() + path;
    }
}